// src/main/java/com/bookmanager/dao/BorrowDAO.java
package com.bookmanager.dao;

import com.bookmanager.util.DatabaseUtil;
import java.sql.*;

public class BorrowDAO {

    public boolean borrowBook(String userId, int bookId) {
        Connection conn = null;
        try {
            conn = DatabaseUtil.getConnection();
            conn.setAutoCommit(false);

            System.out.println("🔍 开始借阅流程: userId=" + userId + ", bookId=" + bookId);

            // 1. 检查图书是否可借
            if (!isBookAvailable(bookId, conn)) {
                System.out.println("❌ 图书不可借: bookId=" + bookId);
                return false;
            }

            // 2. 检查用户是否已经借阅了这本书且未归还
            if (hasUserBorrowedBook(userId, bookId, conn)) {
                System.out.println("❌ 用户已借阅此书且未归还: userId=" + userId + ", bookId=" + bookId);
                return false;
            }

            // 3. 插入借阅记录
            String borrowSql = "INSERT INTO borrow_records (user_id, book_id, borrow_date, due_date, status) " +
                    "VALUES (?, ?, NOW(), DATE_ADD(NOW(), INTERVAL 30 DAY), ?)";

            try (PreparedStatement borrowStmt = conn.prepareStatement(borrowSql)) {
                borrowStmt.setString(1, userId);
                borrowStmt.setInt(2, bookId);
                borrowStmt.setString(3, "borrowed"); // 明确设置状态
                int rows = borrowStmt.executeUpdate();
                System.out.println("✅ 借阅记录插入成功，影响行数: " + rows);
            }

            // 4. 更新图书的可借数量
            String updateSql = "UPDATE books SET available_copies = available_copies - 1, status = CASE WHEN available_copies - 1 = 0 THEN 'borrowed' ELSE 'available' END WHERE book_id = ? AND available_copies > 0";
            try (PreparedStatement updateStmt = conn.prepareStatement(updateSql)) {
                updateStmt.setInt(1, bookId);
                int updated = updateStmt.executeUpdate();
                if (updated == 0) {
                    System.out.println("❌ 更新图书数量失败");
                    conn.rollback();
                    return false;
                }
                System.out.println("✅ 图书数量更新成功");
            }

            conn.commit();
            System.out.println("✅ 借阅成功: userId=" + userId + ", bookId=" + bookId);
            return true;

        } catch (SQLException e) {
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            System.out.println("❌ 借阅失败: " + e.getMessage());
            System.out.println("❌ SQL状态: " + e.getSQLState());
            System.out.println("❌ 错误代码: " + e.getErrorCode());
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.setAutoCommit(true);
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean returnBook(String userId, int bookId) {
        Connection conn = null;
        try {
            conn = DatabaseUtil.getConnection();
            conn.setAutoCommit(false);

            System.out.println("🔍 开始归还流程: userId=" + userId + ", bookId=" + bookId);

            // 1. 更新借阅记录状态
            String returnSql = "UPDATE borrow_records SET return_date = NOW(), status = ? " +
                    "WHERE user_id = ? AND book_id = ? AND status = ?";

            try (PreparedStatement returnStmt = conn.prepareStatement(returnSql)) {
                returnStmt.setString(1, "returned");
                returnStmt.setString(2, userId);
                returnStmt.setInt(3, bookId);
                returnStmt.setString(4, "borrowed");
                int updated = returnStmt.executeUpdate();
                if (updated == 0) {
                    System.out.println("❌ 没有找到对应的借阅记录");
                    conn.rollback();
                    return false;
                }
                System.out.println("✅ 借阅记录更新成功");
            }

            // 2. 更新图书的可借数量
            String updateSql = "UPDATE books SET available_copies = available_copies + 1, status = 'available' WHERE book_id = ?";
            try (PreparedStatement updateStmt = conn.prepareStatement(updateSql)) {
                updateStmt.setInt(1, bookId);
                updateStmt.executeUpdate();
                System.out.println("✅ 图书数量更新成功");
            }

            conn.commit();
            System.out.println("✅ 归还成功: userId=" + userId + ", bookId=" + bookId);
            return true;

        } catch (SQLException e) {
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            System.out.println("❌ 归还失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.setAutoCommit(true);
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private boolean isBookAvailable(int bookId, Connection conn) throws SQLException {
        String sql = "SELECT available_copies FROM books WHERE book_id = ? AND available_copies > 0";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, bookId);
            ResultSet rs = stmt.executeQuery();
            boolean available = rs.next() && rs.getInt("available_copies") > 0;
            System.out.println("📚 图书可用性检查: bookId=" + bookId + ", available=" + available);
            return available;
        }
    }

    private boolean hasUserBorrowedBook(String userId, int bookId, Connection conn) throws SQLException {
        String sql = "SELECT COUNT(*) FROM borrow_records WHERE user_id = ? AND book_id = ? AND status = 'borrowed'";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, userId);
            stmt.setInt(2, bookId);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                boolean hasBorrowed = rs.getInt(1) > 0;
                System.out.println("👤 用户借阅检查: userId=" + userId + ", bookId=" + bookId + ", hasBorrowed=" + hasBorrowed);
                return hasBorrowed;
            }
            return false;
        }
    }
}